package com.hunttown.mes.manage.controller._basic;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.common.utils.ChineseToPinyinUtils;
import com.hunttown.mes.common.utils.JSONUtils;
import com.hunttown.mes.manage.cache.ManageRightMenuCacheData;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.service.AnalysisManageRightMenuManageService;
import com.hunttown.mes.rpc.domain.AnalysisManageRightMenuDTO;
import com.hunttown.mes.rpc.domain.enums.ProgramModuleEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @title: 菜单管理
 * @author: wangjunfu
 * @date: 2018-10-26 15:14:20
 * @description:
 */
@Controller
@RequestMapping(value = "/basic/managemenu")
public class ManageMenuController {

    private final static Logger logger = LoggerFactory.getLogger(ManageMenuController.class);

    private final AnalysisManageRightMenuManageService manageRightMenuService;

    @Autowired
    public ManageMenuController(AnalysisManageRightMenuManageService manageRightMenuService) {
        this.manageRightMenuService = manageRightMenuService;
    }

    //region 首页
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model) {
        return "basic/managemenu/index";
    }

    // 左树
    @RequestMapping(value = "/left_tree", method = RequestMethod.GET)
    public String leftTree(Model model) {
        List<String> menuList = manageRightMenuService.createCateTree(0, 0);
        model.addAttribute("menuList", menuList);

        return "basic/managemenu/left_tree";
    }
    //endregion

    //region 编辑
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, Integer id, Integer parentId) {
        id = id == null ? 0 : id;

        AnalysisManageRightMenuDTO obj = new AnalysisManageRightMenuDTO();
        obj.setId(id);
        obj.setParentId(parentId);

        if (id > 0) {
            obj = manageRightMenuService.getById(id);
        }

        model.addAttribute("menuObj", obj);

        String parentInfo = "新增";

        if (id > 0 || parentId > 0) {
            parentInfo = manageRightMenuService.getParentInfo(id > 0 ? id : parentId);
        }
        if (id == 0 && parentId > 0) {
            parentInfo = String.format("%s > 新增", parentInfo);
        }
        model.addAttribute("parentInfo", parentInfo);

        //模块
        model.addAttribute("programModuleList", ProgramModuleEnum.getEnumList());

        return "basic/managemenu/edit";
    }

    // 保存
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, AnalysisManageRightMenuDTO objDTO) {

        //结果返回，结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();
        try {
            if (objDTO.getPathType() == null) {
                objDTO.setPathType(0);
            }
            if (objDTO.getIsFrontShow() == null) {
                objDTO.setIsFrontShow(0);
            }
            if (objDTO.getOpenNew() == null) {
                objDTO.setOpenNew(0);
            }
            if (objDTO.getStopFlag() == null) {
                objDTO.setStopFlag(0);
            }

            objDTO.setMenuType(0); //默认菜单

            //代码唯一检验
            AnalysisManageRightMenuDTO obj = manageRightMenuService.getByMenuCode(objDTO.getMenuNameEn());
            if (obj != null && obj.getId() > 0 && !Objects.equals(obj.getId(), objDTO.getId())) {   //不能是自己本身
                //说明已经有此记录了，不能插入。
                map = OperateCode.CompositionResult(map, -10, "此菜单代码已存在，请重新输入！");
                result = JSONUtils.toJSON(map);
                return result;
            }

            //设置初始值
            objDTO.setLastUpdatePeople(AdminBaseClass.getPin(request));
            objDTO.setLastUpdateTime(new Date());

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                objDTO = manageRightMenuService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            } else {
                //更新
                //将不需要更新的字段设置为NULL
                objDTO.setMenuNameEn(null);

                Boolean isNext = manageRightMenuService.updateInfoById(objDTO);
                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //刷新菜单缓存
            ManageRightMenuCacheData.init();

            //操作成功 结果返回
            map.put("id", objDTO.getId().toString());
            map.put("parentId", objDTO.getParentId().toString());
            map = OperateCode.CompositionResult(map, 1);

            result = JSONUtils.toJSON(map);
            return result;
        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 删除
    @RequestMapping(value = "/deleteInfo", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(Integer id) {
        //结果返回，结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = manageRightMenuService.delete(id);

            //刷新菜单缓存
            ManageRightMenuCacheData.init();

            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 获取菜单代码
    @RequestMapping(value = "/getMenuCode", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getMenuCode(Integer parentId, String currMenuName) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        //取出当前分类的父级，一直到顶级
        AnalysisManageRightMenuDTO parentDto;
        List<AnalysisManageRightMenuDTO> list = new ArrayList<>();

        AnalysisManageRightMenuDTO item = new AnalysisManageRightMenuDTO();
        item.setParentId(parentId);
        item.setMenuName(currMenuName);
        list.add(item);

        parentDto = item;
        while (parentDto.getParentId() > 0) {
            parentDto = manageRightMenuService.getById(parentDto.getParentId());
            list.add(parentDto);
        }

        //原则：一级分类（首大写）-二级分类（首大写）-三级分类（全大写）-四级分类（全大写）
        StringBuilder py = new StringBuilder();

        int j = 0;
        for (int i = list.size(); i > 0; i--) {
            j++;

            String name = list.get(i - 1).getMenuName();
            name = name.replace("&ensp;", "").replace(" ", "");

            if (list.size() <= 3 || (list.size() == 4 && j <= 3)) {
                if (list.size() == j || (list.size() == 4 && j == 3)) {
                    py.append(ChineseToPinyinUtils.ToFirstChar(name).toUpperCase());
                } else {
                    py.append(ChineseToPinyinUtils.ToFirstChar(name).toUpperCase().substring(0, 1));
                }
            } else {
                py.append(ChineseToPinyinUtils.ToFirstChar(name).toUpperCase());
            }
            if (i > 1) {
                py.append("-");
            }
        }

        map.put("menuCode", py.toString());
        map.put("returnCode", 1);

        return map;
    }
    //endregion
}